package cn.darkhorse.device.service.impl;

import cn.darkhorse.common.constant.CommonConstant;
import cn.darkhorse.device.mapper.MesSpareTypeMapper;
import cn.darkhorse.device.pojo.MesSpareParts;
import cn.darkhorse.device.pojo.MesSpareType;
import cn.darkhorse.device.service.MesSparePartsService;
import cn.darkhorse.device.service.MesSpareTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 备件类型 服务实现类
 * </p>
 *
 * @author maoguanjun
 * @since 2022-11-11
 */
@Service
public class MesSpareTypeServiceImpl extends ServiceImpl<MesSpareTypeMapper, MesSpareType> implements MesSpareTypeService {

    @Resource
    private MesSparePartsService mesSparePartsService;
    /**
     * 列表
     *
     * @param name
     * @return
     */
    @Override
    public List<MesSpareType> listAll(String name,String orderType) {
        LambdaQueryWrapper<MesSpareType> wrapper=new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(name)){
            wrapper.like(MesSpareType::getName,name);
        }
        if(CommonConstant.ORDER_TYPE_ASC.equals(orderType)){
            wrapper.orderByAsc(MesSpareType::getGmtCreate);
        }else{
            wrapper.orderByDesc(MesSpareType::getGmtCreate);
        }
        return list(wrapper);
    }

    /**
     * 保存
     *
     * @param type
     */
    @Override
    public boolean saveType(MesSpareType type) {
        if(null==type.getId()){
            type.setCreator(type.getCreator());
        }
        LambdaQueryWrapper<MesSpareType> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesSpareType::getName,type.getName());
        if(null!=type.getId()){
            type.setGmtModify(LocalDateTime.now());
            MesSpareType typeOld=getById(type.getId());
            if(!type.getCode().equals(typeOld.getCode())){
                throw  new ServiceException("编码不可更改");
            }
            wrapper.ne(MesSpareType::getId,type.getId());
        }
        long count=count(wrapper);
        if(count>0){
            throw new ServiceException("名称已存在！");
        }

        return saveOrUpdate(type);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean delete(Long id) {
        LambdaQueryWrapper<MesSpareParts> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(MesSpareParts::getType,id);
        long count=mesSparePartsService.count(wrapper);
        if(count>0){
            throw new ServiceException("分类已引用，不可删除!");
        }
        return removeById(id);
    }
}
